package org.maverick.persistence.filter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class FindByExample {
	
	private static String SUFFIX_GET = "get"; 

	@SuppressWarnings({ "rawtypes" })
	public static QueryFilter create(Object object) {
		
		try {
		
			QueryFilter queryFilter = new QueryFilter();
			
			Class clazz = object.getClass();
			Field fields[] = clazz.getDeclaredFields();
			
			for (Field field : fields) {
				
				for (Annotation annotation : field.getAnnotations()) {
					
					if (annotation instanceof javax.persistence.Column) {
						
						String invokeMethod = SUFFIX_GET.concat(field.getName().substring(0,1).toUpperCase().trim().concat(field.getName().substring(1).trim()));  
						
						Method method = object.getClass().getMethod(invokeMethod, null);
						
						String key = field.getType().equals(String.class) ?  field.getName() + QueryFilter.LIKE : field.getName();
						
						Object value = method.invoke(object, null);
						
						if (value != null)
							queryFilter.add(key, value);
						
					}
					
					if (annotation instanceof javax.persistence.JoinColumn) {
						
						String invokeMethod = SUFFIX_GET.concat(field.getName().substring(0,1).toUpperCase().trim().concat(field.getName().substring(1).trim()));
						
						Method method = object.getClass().getMethod(invokeMethod, null);
						
						Object objectChildren = method.invoke(object, null);
						
						if(objectChildren != null){
						
							Class clazzChildren = objectChildren.getClass();
							
							Field [] fieldsChildren = clazzChildren.getDeclaredFields();
							
							for (Field fieldChildren : fieldsChildren) {
								
								for (Annotation annotationChildren : fieldChildren.getAnnotations()) {
									
									if (annotationChildren instanceof javax.persistence.Column) {
										
										String invokeMethodChildren = SUFFIX_GET.concat(fieldChildren.getName().substring(0,1).toUpperCase().trim().concat(fieldChildren.getName().substring(1).trim()));  
										
										Method methodChildren = objectChildren.getClass().getMethod(invokeMethodChildren, null);
										
										String key = fieldChildren.getType().equals(String.class) ?  field.getName() + "." + fieldChildren.getName() + QueryFilter.LIKE : field.getName() + "." + fieldChildren.getName();
										
										Object valueChildren = methodChildren.invoke(objectChildren, null);
										
										if (valueChildren != null)
											queryFilter.add(key, valueChildren);
										
									}
								}
							}
						}
					}
				}
			}
			
			return queryFilter;
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
		
	}
	
}